/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.api.common;

import static com.alibaba.fastjson.util.TypeUtils.castToBigDecimal;
import static com.alibaba.fastjson.util.TypeUtils.castToBigInteger;
import static com.alibaba.fastjson.util.TypeUtils.castToBoolean;
import static com.alibaba.fastjson.util.TypeUtils.castToByte;
import static com.alibaba.fastjson.util.TypeUtils.castToBytes;
import static com.alibaba.fastjson.util.TypeUtils.castToDate;
import static com.alibaba.fastjson.util.TypeUtils.castToDouble;
import static com.alibaba.fastjson.util.TypeUtils.castToFloat;
import static com.alibaba.fastjson.util.TypeUtils.castToInt;
import static com.alibaba.fastjson.util.TypeUtils.castToLong;
import static com.alibaba.fastjson.util.TypeUtils.castToShort;
import static com.alibaba.fastjson.util.TypeUtils.castToSqlDate;
import static com.alibaba.fastjson.util.TypeUtils.castToTimestamp;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.annotation.JSONField;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.util.TypeUtils;


/**
 * $.ajax后需要接受的JSON
 * 
 * @author
 * 
 */
public class ReqJson extends JSON implements Map<String, Object>, Cloneable, Serializable, InvocationHandler {

	private static final long serialVersionUID = 1L;
	private static final int DEFAULT_INITIAL_CAPACITY = 16;

	private final Map<String, Object> map;

	public ReqJson() {
		this(DEFAULT_INITIAL_CAPACITY, false);
	}

	public ReqJson(Map<String, Object> map) {
		this.map = map;
	}

	public ReqJson(boolean ordered) {
		this(DEFAULT_INITIAL_CAPACITY, ordered);
	}

	public ReqJson(int initialCapacity) {
		this(initialCapacity, false);
	}

	public ReqJson(int initialCapacity, boolean ordered) {
		if (ordered) {
			map = new LinkedHashMap<String, Object>(initialCapacity);
		} else {
			map = new HashMap<String, Object>(initialCapacity);
		}
	}

	public int size() {
		return map.size();
	}

	public boolean isEmpty() {
		return map.isEmpty();
	}

	public boolean containsKey(Object key) {
		return map.containsKey(key);
	}

	public boolean containsValue(Object value) {
		return map.containsValue(value);
	}

	public Object get(Object key) {
		Object val = map.get(key);

		if (val == null && key instanceof Number) {
			val = map.get(key.toString());
		}

		return val;
	}

	public JSONObject getJSONObject(String key) {
        Object value = map.get(key);

        if (value instanceof JSONObject) {
            return (JSONObject) value;
        }

        if (value instanceof String) {
            return JSON.parseObject((String) value);
        }

        return (JSONObject) toJSON(value);
    }
	
	public JSONArray getJSONArray(String key) {
		Object value = map.get(key);

		if (value instanceof JSONArray) {
			return (JSONArray) value;
		}

		if (value instanceof String) {
			return (JSONArray) JSON.parse((String) value);
		}

		return (JSONArray) toJSON(value);
	}

	public <T> T getObject(String key, Class<T> clazz) {
		Object obj = map.get(key);
		return TypeUtils.castToJavaBean(obj, clazz);
	}

	public <T> T getObject(String key, Type type) {
		Object obj = map.get(key);
		return TypeUtils.cast(obj, type, ParserConfig.getGlobalInstance());
	}

	public <T> T getObject(String key, TypeReference typeReference) {
		Object obj = map.get(key);
		if (typeReference == null) {
			return (T) obj;
		}
		return TypeUtils.cast(obj, typeReference.getType(), ParserConfig.getGlobalInstance());
	}

	public Boolean getBoolean(String key) {
		Object value = get(key);

		if (value == null) {
			return null;
		}

		return castToBoolean(value);
	}

	public byte[] getBytes(String key) {
		Object value = get(key);

		if (value == null) {
			return null;
		}

		return castToBytes(value);
	}

	public boolean getBooleanValue(String key) {
		Object value = get(key);

		Boolean booleanVal = castToBoolean(value);
		if (booleanVal == null) {
			return false;
		}

		return booleanVal.booleanValue();
	}

	public Byte getByte(String key) {
		Object value = get(key);

		return castToByte(value);
	}

	public byte getByteValue(String key) {
		Object value = get(key);

		Byte byteVal = castToByte(value);
		if (byteVal == null) {
			return 0;
		}

		return byteVal.byteValue();
	}

	public Short getShort(String key) {
		Object value = get(key);

		return castToShort(value);
	}

	public short getShortValue(String key) {
		Object value = get(key);

		Short shortVal = castToShort(value);
		if (shortVal == null) {
			return 0;
		}

		return shortVal.shortValue();
	}

	public Integer getInteger(String key) {
		Object value = get(key);

		return castToInt(value);
	}

	public int getIntValue(String key) {
		Object value = get(key);

		Integer intVal = castToInt(value);
		if (intVal == null) {
			return 0;
		}

		return intVal.intValue();
	}

	public Long getLong(String key) {
		Object value = get(key);

		return castToLong(value);
	}

	public long getLongValue(String key) {
		Object value = get(key);

		Long longVal = castToLong(value);
		if (longVal == null) {
			return 0L;
		}

		return longVal.longValue();
	}

	public Float getFloat(String key) {
		Object value = get(key);

		return castToFloat(value);
	}

	public float getFloatValue(String key) {
		Object value = get(key);

		Float floatValue = castToFloat(value);
		if (floatValue == null) {
			return 0F;
		}

		return floatValue.floatValue();
	}

	public Double getDouble(String key) {
		Object value = get(key);

		return castToDouble(value);
	}

	public double getDoubleValue(String key) {
		Object value = get(key);

		Double doubleValue = castToDouble(value);
		if (doubleValue == null) {
			return 0D;
		}

		return doubleValue.doubleValue();
	}

	public BigDecimal getBigDecimal(String key) {
		Object value = get(key);

		return castToBigDecimal(value);
	}

	public BigInteger getBigInteger(String key) {
		Object value = get(key);

		return castToBigInteger(value);
	}

	public String getString(String key) {
		Object value = get(key);

		if (value == null) {
			return null;
		}

		return value.toString();
	}

	public Date getDate(String key) {
		Object value = get(key);

		return castToDate(value);
	}

	public java.sql.Date getSqlDate(String key) {
		Object value = get(key);

		return castToSqlDate(value);
	}

	public java.sql.Timestamp getTimestamp(String key) {
		Object value = get(key);

		return castToTimestamp(value);
	}

	public Object put(String key, Object value) {
		return map.put(key, value);
	}

	public ReqJson fluentPut(String key, Object value) {
		map.put(key, value);
		return this;
	}

	public void putAll(Map<? extends String, ? extends Object> m) {
		map.putAll(m);
	}

	public ReqJson fluentPutAll(Map<? extends String, ? extends Object> m) {
		map.putAll(m);
		return this;
	}

	public void clear() {
		map.clear();
	}

	public ReqJson fluentClear() {
		map.clear();
		return this;
	}

	public Object remove(Object key) {
		return map.remove(key);
	}

	public ReqJson fluentRemove(Object key) {
		map.remove(key);
		return this;
	}

	public Set<String> keySet() {
		return map.keySet();
	}

	public Collection<Object> values() {
		return map.values();
	}

	public Set<Map.Entry<String, Object>> entrySet() {
		return map.entrySet();
	}

	@Override
	public Object clone() {
		return new ReqJson(map instanceof LinkedHashMap //
				? new LinkedHashMap<String, Object>(map) //
				: new HashMap<String, Object>(map));
	}

	public boolean equals(Object obj) {
		return this.map.equals(obj);
	}

	public int hashCode() {
		return this.map.hashCode();
	}

	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Class<?>[] parameterTypes = method.getParameterTypes();
		if (parameterTypes.length == 1) {
			if (method.getName().equals("equals")) {
				return this.equals(args[0]);
			}

			Class<?> returnType = method.getReturnType();
			if (returnType != void.class) {
				throw new JSONException("illegal setter");
			}

			String name = null;
			JSONField annotation = method.getAnnotation(JSONField.class);
			if (annotation != null) {
				if (annotation.name().length() != 0) {
					name = annotation.name();
				}
			}

			if (name == null) {
				name = method.getName();

				if (!name.startsWith("set")) {
					throw new JSONException("illegal setter");
				}

				name = name.substring(3);
				if (name.length() == 0) {
					throw new JSONException("illegal setter");
				}
				name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
			}

			map.put(name, args[0]);
			return null;
		}

		if (parameterTypes.length == 0) {
			Class<?> returnType = method.getReturnType();
			if (returnType == void.class) {
				throw new JSONException("illegal getter");
			}

			String name = null;
			JSONField annotation = method.getAnnotation(JSONField.class);
			if (annotation != null) {
				if (annotation.name().length() != 0) {
					name = annotation.name();
				}
			}

			if (name == null) {
				name = method.getName();
				if (name.startsWith("get")) {
					name = name.substring(3);
					if (name.length() == 0) {
						throw new JSONException("illegal getter");
					}
					name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
				} else if (name.startsWith("is")) {
					name = name.substring(2);
					if (name.length() == 0) {
						throw new JSONException("illegal getter");
					}
					name = Character.toLowerCase(name.charAt(0)) + name.substring(1);
				} else if (name.startsWith("hashCode")) {
					return this.hashCode();
				} else if (name.startsWith("toString")) {
					return this.toString();
				} else {
					throw new JSONException("illegal getter");
				}
			}

			Object value = map.get(name);
			return TypeUtils.cast(value, method.getGenericReturnType(), ParserConfig.getGlobalInstance());
		}

		throw new UnsupportedOperationException(method.toGenericString());
	}

	public Map<String, Object> getInnerMap() {
		return this.map;
	}
	
	public static ReqJson parseReqJson(String text) {
        Object obj = parse(text);
        if (obj instanceof ReqJson) {
            return (ReqJson) obj;
        }

        try {
            return (ReqJson) JSON.toJSON(obj);
        } catch (RuntimeException e) {
            throw new JSONException("can not cast to ReqJson.", e);
        }
    }
	
	/**
	 * 请求指令
	 * @return
	 */
	public String getCmd() {
		return getString("cmd");
	}
	
	/**
	 * 当前页码
	 * @return
	 */
	public int getPageNo() {
		int value = getIntValue("pageNo");
		return value > 0 ? value : 1;
	}
	
	/**
	 * 页面大小
	 * @return
	 */
	public int getPageSize() {
		int value = getIntValue("pageSize");
		return value > 0 ? value : 10;
	}
	
	/**
	 * 用户ID
	 * @return
	 */
	public String getUid() {
		return getString("uid");
	}

}
